package atguigu.web;

import atguigu.pojo.User;
import atguigu.service.UserService;
import atguigu.service.impl.UserServiceImpl;
import atguigu.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数username
        String username = req.getParameter("username");
        //调用userService.existsUsername()
        boolean existUsername = userService.existUsername(username);
        //把返回的结果封装成为map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existUsername",existUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }

    //注销功能
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁Session中用户登录的信息
        req.getSession().invalidate();
        //2.重定向到首页（或者登录页面）
        resp.sendRedirect(req.getContextPath()+"/pages/user/login.jsp");
        //   跳回登录页面
       // req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
    }

    //处理登录功能
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        // 调用 userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password));
            // 如果等于null,说明登录 失败!
            if (loginUser == null||code==null) {
                //把错误信息，和回显的表单信息，保存到Retquest域中
                req.setAttribute("msg","用户名或密码错误");
                req.setAttribute("username",username);
                //   跳回登录页面
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            } else if(token!=null && token.equalsIgnoreCase(code)) {
                //保存用户登录的信息到Session域中
                req.getSession().setAttribute("user",loginUser);
                // 登录 成功
                //跳到成功页面login_success.jsp
                req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
            }else {
                //把错误信息，和回显的表单信息，保存到Retquest域中
                req.setAttribute("msg","验证码错误");
                req.setAttribute("username",username);
                //   跳回登录页面
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
            }


    }
    //处理注册功能
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //1.获取请求的参数  前端用户注册输入的参数，用户名和密码
        String username = req.getParameter("username");//与.jsp文件中 input中name属性的值统一
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        User user = new User();
        WebUtils.copyParamToBean(req.getParameterMap(),user);
        //2.检查验证码是否正确
        if (token!=null && token.equalsIgnoreCase(code)) {
//        3、检查 用户名是否可用
            if (userService.existUsername(username)) {
                //把回显信息保存到域中
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
//        跳回注册页面
                req.getRequestDispatcher("/pages/user/register.jsp").forward(req, resp);
            } else {
                //      可用
//                调用Sservice保存到数据库
                userService.registUser(new User(null, username, password));
//
//        跳到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }

        }else {
            //把回显信息保存到域中
            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            //跳转到注册页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }

}
